package blog.model;

import blog.beans.Post;
import blog.utils.HibernateUtil;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author johdah <info@johandahlberg.com>
 */
public class PostHelper {
    Session session = null;
    
    public PostHelper() {
        super();
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }
    
    public List<Post> getPosts() {
        List<Post> posts = null;
        
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from Post");
            posts = (List<Post>) q.list();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        return posts;
    }
    
    public List<Post> getPostsByAuthorId(Integer author_id) {
        List<Post> posts = null;
        
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from Post as post where post.UId=" + author_id);
            posts = (List<Post>) q.list();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        return posts;
    }
    
    public Post getPostsById(Integer post_id) {
        Post post = null;
        
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from Post as post where post.PId=" + post_id);
            post = (Post) q.uniqueResult();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        return post;
    }
    
    public boolean setPost(Post post) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(post);
            tx.commit();
            return true;
        } catch(Exception e) {
            return false;
        }
    }
}